#!/user/bin/env python3
# -*- coding: utf-8 -*-
import random

import matplotlib
from PIL import ImageDraw, ImageFont

# Setings
matplotlib.rc('font', **{'size': 11})
matplotlib.use('Agg')  # for writing to files only
from PIL import Image
import cv2
import numpy as np
from flask import Flask, request

app = Flask(__name__)


# 接收绘图请求发送过来的数据
@app.route("/requestDrawing", methods=['POST'])
def draw():
    global label, ch_text, line_thickness
    map = {'person': '人', 'laptop': '笔记本电脑', 'chair': '椅子', 'bus': '巴士', 'tie': '领带', 'fire hydrant': '消防栓',
           'object': '物体'}
    if request.method == 'POST':
        data = request.get_data()
        string = str(data)
        # 首选切割 字符串
        convert = string[1:]
        print(convert)
        # & 分割转列表
        list = convert.split('&')
        c1, c2, color = (), (), ()

        for assignment in list:
            if assignment.__contains__("c1"):
                split = assignment.split('=')
                c1 += (int(split[1]),)
            elif assignment.__contains__("c2"):
                split = assignment.split('=')
                c2 += (int(split[1]),)
            elif assignment.__contains__("color"):
                split = assignment.split('=')
                color += (int(split[1]),)
            elif assignment.__contains__("ch_text"):
                split = assignment.split('=')
                ch_text = split[1]
            elif assignment.__contains__("line_thickness"):
                split = assignment.split('=')
                line_thickness = int((split[1])[0:1])
            elif assignment.__contains__("label"):
                split = assignment.split('=')
                label = split[1]
        path = 'F:/convertImage/lxy.jpg'
        img = cv2.imread(path)
        if ch_text in map:
            ch_text = map[ch_text]
        im0 = plot_one_box(c1, c2, img, color=color, label=label, ch_text=ch_text, line_thickness=line_thickness)
        cv2.imwrite("F:/convertImage/lxy.jpg", im0)
        return "成功"


# 绘图
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    # 图像从OpenCV格式转换成PIL格式
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)
    fontText = ImageFont.truetype("../Font/simhei.ttf", textSize, encoding="utf-8")
    draw.text((left, top), text, textColor, font=fontText)
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


# 绘图
def plot_one_box(c1, c2, img, color=None, label=None, ch_text=None, line_thickness=None):
    # Plots one bounding box on image img
    global img_text
    tl = line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness
    color = color or [random.randint(0, 255) for _ in range(3)]
    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
    if label:
        tf = max(tl - 6, 1)  # font thickness
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 6, thickness=tf)[0]
        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled
        # cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)
        img_text = cv2ImgAddText(img, ch_text, c1[0], c2[1], (255, 255, 255), 25)  # todo: 文字以左上点坐标为准，即：c1[0], c2[1]
    return img_text


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5002)
